package com.ctshk.rpc.cms.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.redis.KeyUtil;
import com.ctshk.rpc.cms.constant.CmsConstant;
import com.ctshk.rpc.cms.dto.ContentDTO;
import com.ctshk.rpc.cms.entity.Content;
import com.ctshk.rpc.cms.mapper.ContentMapper;
import com.ctshk.rpc.cms.req.ContentAddReq;
import com.ctshk.rpc.cms.req.ContentQueryReq;
import com.ctshk.rpc.cms.req.ContentUpdateReq;
import com.ctshk.rpc.cms.req.UpdateStatusReq;
import com.ctshk.rpc.cms.service.IContentService;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.service.ISysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 内容管理表 服务实现类
 * </p>
 *
 * @author LiZhiming
 * @since 2021-04-23
 */
@DubboService
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements IContentService {
    @DubboReference
    private ISysUserService sysUserService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Result insert(ContentAddReq req, TokenUser tu) {
        Content content = EntityUtil.copy(req, Content.class);
        LocalDateTime now = LocalDateTime.now();
        Long id = IdWorker.getId();
        content.setCreateId(tu.getId());
        content.setGmtCreate(now);
        content.setId(id);
        content.setBrowseCount(0);//浏览记录0条
        content.setIsDeleted(IsDeletedCode.NO.getCode());
        int insert = baseMapper.insert(content);
        if (insert > 0) {
            //做了修改操作如果存在这个缓存就清除缓存
            Set<String> keysRecommend = redisTemplate.keys(KeyUtil.genLikeKey(CmsConstant.CMS_CONTENT_REDIS_KEY));
            if (CollUtil.isNotEmpty(keysRecommend)) {
                redisTemplate.delete(keysRecommend);
            }
            return Result.success(id);
        }
        return Result.failed(SystemError.CMS_23000);
    }

    @Override
    public Result<ContentDTO> queryById(String contentId) {
        ContentDTO b = null;
        QueryWrapper<Content> qw = new QueryWrapper<>();
        qw.lambda().eq(Content::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(Content::getId, contentId);
        Content content = baseMapper.selectOne(qw);
        if (content != null) {
            b = EntityUtil.copy(content, ContentDTO.class);
        }
        return Result.success(b);
    }

    @Override
    public PageResponse<ContentDTO> queryList(ContentQueryReq req) {
        Page<Content> page = new Page(req.getPageNo(), req.getPageSize());
        QueryWrapper<Content> qw = new QueryWrapper();
        qw.lambda().eq(Content::getIsDeleted, IsDeletedCode.NO.getCode())
                .eq(req.getArticleClassificationId() != null, Content::getArticleClassificationId, req.getArticleClassificationId())
                .eq(req.getArticleClassificationName() != null, Content::getArticleClassificationName, req.getArticleClassificationName())
                .eq(req.getStatus() != null, Content::getStatus, req.getStatus())
                .eq(req.getArticleTitle() != null, Content::getArticleTitle, req.getArticleTitle());
        Page<Content> contentPage = baseMapper.selectPage(page, qw);
        if (CollectionUtils.isNotEmpty(contentPage.getRecords())) {
            List<ContentDTO> cententTtos = EntityUtil.copyList(contentPage.getRecords(), ContentDTO.class);
            for (ContentDTO item : cententTtos) {
                UserDTO userDTO = sysUserService.loadUserInfo(item.getCreateId(), 1);
                if (userDTO != null) {
                    item.setUserName(userDTO.getCnSurname() + userDTO.getCnName());
                }
            }
            return new PageResponse<>(cententTtos,
                    page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                    page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
        }
        return new PageResponse<>(null,
                page.getCurrent() == 1, page.getTotal() <= (page.getCurrent() *
                page.getSize()), page.getTotal(), page.getCurrent(), page.getSize());
    }

    @Override
    public Result update(ContentUpdateReq req, TokenUser tu) {
        Content content = baseMapper.selectById(req.getId());
        if (content != null) {
            LocalDateTime now = LocalDateTime.now();
            Content copy = EntityUtil.copy(req, Content.class);
            copy.setModifiedId(tu.getId());
            copy.setGmtModified(now);
            copy.setBrowseCount(content.getBrowseCount());
            int i = baseMapper.updateById(copy);
            if (i > 0) {
                //做了修改操作如果存在这个缓存就清除缓存
                Set<String> keysRecommend = redisTemplate.keys(KeyUtil.genLikeKey(CmsConstant.CMS_CONTENT_REDIS_KEY));
                if (CollUtil.isNotEmpty(keysRecommend)) {
                    redisTemplate.delete(keysRecommend);
                }
                return Result.success(req.getId());
            }
        }
        return Result.failed(SystemError.CMS_23002);
    }

    @Override
    public Result updateStatusById(UpdateStatusReq req) {
        int i = baseMapper.updateStatusById(req.getId(), req.getStatus());
        if (i > 0) {
            Content content = baseMapper.selectById(req.getId());
            if (content != null) {
                //做了修改操作如果存在这个缓存就清除缓存
                Set<String> keysRecommend = redisTemplate.keys(KeyUtil.genLikeKey(CmsConstant.CMS_CONTENT_REDIS_KEY));
                if (CollUtil.isNotEmpty(keysRecommend)) {
                    redisTemplate.delete(keysRecommend);
                }
            }
        }
        return Result.success(i);
    }

    @Override
    public Result updateCountById(Long id) {
        int i = baseMapper.updateCountById(id);
        return Result.success(i);
    }
}
